/**
 * 自动化生成API
 */
import fs from 'node:fs';
import path from 'node:path';

const apiTemplate = `import BaseRequest from "../BaseRequest";

class ##className## extends BaseRequest {
##methods##
}

export default ##className##;
`;

const methodTemplate = `  async ##apiName##(##params##) {
    const url = ##url##;
    const data = await this.##method##(url, ##data##);
    return data;
  }`;

const apiConfig = [
  {
    className: 'UserRequest',
    modules: [
      {
        apiName: 'getUserInfo',
        url: '/user/info/:userId',
        method: 'GET',
        params: 'userId',
        data: ''
      },
      {
        apiName: 'updateUserAvatar',
        url: '/user/avatar/:userId',
        method: 'POST',
        params: 'userId, formData',
        data: 'formData'
      }
    ]
  }
];

apiConfig.forEach((config) => {
  let fileContent = apiTemplate.replace('##className##', config.className);
  let methods = '';
  config.modules.forEach((api) => {
    let methodContent = methodTemplate
      .replace('##apiName##', api.apiName)
      .replace('##url##', api.url)
      .replace('##method##', api.method)
      .replace('##params##', api.params)
      .replace('##data##', api.data);
    methods += methodContent + '\n';
  });
  fileContent = fileContent.replace('##methods##', methods);

  const filePath = path.join(__dirname, `${config.className}.ts`);
  fs.writeFileSync(filePath, fileContent);
});
